<?php
namespace app\admin\controller;
use app\admin\controller\Common;
use app\admin\model\ArticleKind;
use think\Db;
class Article extends Common
{
	/*
	 *文章栏目列表
	*/
	function articleKindList() {
		$ArticleCat = new ArticleKind(); 
        $cat_list = $ArticleCat->article_kind_list(0, 0, false);
        return view('articleKindList',['cat_list'=>$cat_list]);
	}

	/*
	 *添加编辑文章分类
	*/
	function category() {
 		$act = input('route.act')?input('route.act'):'add';
        $this->assign('act',$act);
        $kind_id = input('route.kind_id');
        $cat_info = array();
        if($kind_id){
            $cat_info = Db::name('article_kind')->where('kind_id='.$kind_id)->find();
            $this->assign('cat_info',$cat_info);
        }
        $ArticleCat = new ArticleKind(); 
        $pid = empty($cat_info['parent_id'])?'':$cat_info['parent_id'];
        $cats = $ArticleCat->article_kind_list(0,$pid,true);
        $this->assign('cat_select',$cats);

        $template = Db::name('template')->where('is_hide=0')->order('sort asc')->select();
        $this->assign('template',$template);

        $article_group = config('article_group');
        $this->assign('article_group',$article_group);
        $article_field = explode('|',$cat_info['article_field']);
        $this->assign('article_field',$article_field);

		return view();
	}

	/*
    **文章分类yu数据
    */
    public function categoryData($data) {
        $formData['kind_id'] = $data['kind_id'];
        $formData['kind_name'] = $data['kind_name'];
        $formData['e_kind_name'] = $data['e_kind_name'];
        $formData['parent_id'] = $data['parent_id'];
        $formData['kind_thumb'] = $data['kind_thumb'];
        $formData['banner_img'] = $data['banner_img'];
        $formData['e_banner_img'] = $data['e_banner_img'];
        $formData['p_banner_img'] = $data['p_banner_img'];
        $formData['kind_template'] = $data['kind_template'];
        $formData['art_template'] = $data['art_template'];
        $formData['kind_info'] = stripslashes($data['kind_info']);
        $formData['e_kind_info'] = stripslashes($data['e_kind_info']);
        $formData['is_hide'] = $data['is_hide'] ? $data['is_hide'] : 0;
        $formData['is_footer'] = $data['is_footer'] ? $data['is_footer'] : 0;
        $formData['sort_order'] = $data['sort_order'] ? $data['sort_order'] : 100;
        $formData['art_num'] = $data['art_num'] ? $data['art_num'] : 6;
        $formData['p_art_num'] = $data['p_art_num'] ? $data['p_art_num'] : 8;
        $formData['keywords'] = $data['keywords'];
        $formData['description'] = $data['description'];
        $formData['link_url'] = $data['link_url'];
        $formData['act'] = $data['act'];
        $formData['web_title'] = $data['web_title'];
        if($data['article_field'] <> ''){
            $formData['article_field'] = implode('|',$data['article_field']);
        }else{
            $formData['article_field'] = '';
        }
        
        return $formData;
    }
	/*
	 *处理文章分类
	*/
	public function categoryHandle(){
        $ArticleCat = new ArticleKind();
        $data = $this->categoryData(request()->post()); 
        // dump($data);exit;
        if($data['act'] == 'add'){      
        	unset($data['act']);     
            $d = db('article_kind')->insertGetId($data);
            $ArticleCat->refresh_cat($d);//修改分类族谱，级别
            $json['status'] = 1;
            $json['message'] = "添加文章分类成功！";
            echo json_encode($json);
            /*********************记录日志***********************/
            addLog(session('user_name').'添加文章分类成功-'.$data['kind_name'].' [ ID:'.$d.' ]');
            return;
        }
        
        if($data['act'] == 'edit')
        {
        	unset($data['act']); 
        	if ($data['kind_id'] == $data['parent_id']) 
			{
        		//$this->error("所选分类的上级分类不能是当前分类",U('Admin/Article/category',array('kind_id'=>$data['kind_id'])));
                $json['status'] = 0;
                $json['message'] = "所选分类的上级分类不能是当前分类！";
                echo json_encode($json);
                return;
        	}
        	$ArticleCat = new ArticleKind();
        	$children = array_keys($ArticleCat->article_kind_list($data['kind_id'], 0, false)); // 获得当前分类的所有下级分类
        	if (in_array($data['parent_id'], $children))
        	{
        		//$this->error("所选分类的上级分类不能是当前分类的子分类",U('Admin/Article/category',array('kind_id'=>$data['kind_id'])));
                $json['status'] = 0;
                $json['message'] = "所选分类的上级分类不能是当前分类的子分类！";
                echo json_encode($json);
                return;
        	}
            $d = db('article_kind')->where(array('kind_id'=>$data['kind_id']))->update($data);
            if($d !== false){
                $ArticleCat->refresh_cat($data['kind_id']);//修改分类族谱，级别
                $json['status'] = 1;
                $json['message'] = "修改文章分类成功！";
                echo json_encode($json);
                /*********************记录日志***********************/
                addLog(session('user_name').'修改文章分类成功-'.$data['kind_name'].' [ ID:'.$data['kind_id'].' ]');
                return;
            }
            
        }
        
        if($data['act'] == 'del'){      	
        	$res = db('article_kind')->where(array('parent_id'=>$data['kind_id']))->select(); 
        	if ($res)
        	{
                $json['status'] = 0;
                $json['message'] = "还有子分类，不能删除！";
                echo json_encode($json);
                return;
        	}
        	$res = db('article')->where(array('kind_id'=>$data['kind_id']))->select();       	      	
        	if ($res)
        	{
                $json['status'] = 0;
                $json['message'] = "非空的分类不允许删除！";
                echo json_encode($json);
                return;
        	}
            $kind = db('article_kind')->where(array('kind_id'=>$data['kind_id']))->find();
        	$r = db('article_kind')->where(array('kind_id'=>$data['kind_id']))->delete();
        	if ($r) {
                $json['status'] = 1;
                $json['message'] = "删除栏目成功！";
                echo json_encode($json);
                /*********************记录日志***********************/
                addLog(session('user_name').'删除文章分类成功-'.$kind['kind_name'].' [ ID:'.$kind['kind_id'].' ]');
                return;
            }
        } 
        
    }

    function getArticleField(){
        $kind_id = input('kind_id');
        $kind = Db::name('article_kind')->field('article_field')->find($kind_id);
        $article_field = '';
        if($kind['article_field'] <> ''){
            $article_field = explode('|',$kind['article_field']);
        }
        $json = array('status'=>1,'article_field'=>$article_field);
        echo json_encode($json);exit;
        
    }

    /*
     *文章列表
    */
    function articleList() { 
        $inputData = input('get.');
        $kind_id = empty($inputData['kind_id'])?0:$inputData['kind_id'];
        $ArticleCat = new ArticleKind();
        $cats = $ArticleCat->article_kind_list(0,0,false);
        $cat_list = $ArticleCat->article_kind_list(0, $kind_id, ture);//搜索条件栏目

        $this->assign('cats',$cats);
        $this->assign('cat_select',$cat_list);
        // dump($cats);exit;
        $res = $list = array();
        $p = empty($_GET['p']) ? 1 : $_GET['p'];
        $size = empty($_REQUEST['size']) ? 25 : $_REQUEST['size'];
        $where = 'is_del=0';
        if ($inputData['kind_id'])
            $where .= " and kind_id=".$inputData['kind_id'];
        if ($inputData['keyword']){
            $where .= " and title like '%".$inputData['keyword']."%'";
            $this->assign('keyword',$inputData['keyword']);
        }
        // dump($where);exit;
        $count = Db::name('article')->where($where)->count();// 查询满足要求的总记录数

        $res = Db::name('article')->where($where)->order('article_id desc')->paginate($size,$count,['query'=>request()->param()])->each(function($item,$key){
            // $item['nickname'] = 'think';
            // $item['category'] = $cats[$item['kind_id']]['kind_name'];
            return $item;
        });
        $page = $res->render();

        $this->assign('list',$res);// 赋值数据集
        $this->assign('page',$page);// 赋值分页输出
        $this->assign('total',$count);// 数据总数

        return view('articleList');
    }
    
    public function article(){
        $ArticleCat = new ArticleKind();
        $act = input('route.act')?input('route.act'):'add';
        $info = array();
        if(input('route.article_id')){
            $article_id = input('route.article_id');
            $info = db('article')->where('article_id='.$article_id)->find();
            $info['pics_arr'] = json_decode($info['pics']);
            $date = $info['add_time'];
            // $thumb_list = json_decode($info['thumb_list']);
            $cats = $ArticleCat->article_kind_list(0,$info['kind_id']);
        } else {
            $date = date('Y-m-d H:i:s',$_SERVER['REQUEST_TIME']);
            $pre_kind = db("config")->where("name='last_add_kind_id'")->find();
            $cats = $ArticleCat->article_kind_list(0,$pre_kind['desc']);
        }

        $this->assign('cat_select',$cats);
        $this->assign('act',$act);
        $this->assign('info',$info);

        // $this->assign('thumb_list',$thumb_list);
        $this->assign('date',$date);// 赋值数据集
        //$this->initEditor();
        return view();
    }

    /*
     *文章数据yu处理
    */
    function articleData($data) {
        $checkData['article_id'] = $data['article_id'];
        $checkData['kind_id'] = $data['kind_id'];
        $checkData['title'] = $data['title'];
        $checkData['sub_title'] = $data['sub_title'];
        $checkData['author'] = $data['author'];
        $checkData['source'] = $data['source'];
        $checkData['add_time'] = $data['add_time'];
        // $checkData['publish_time'] = date('Y-m-d H:i:s');
        // $checkData['hot_label'] = implode(',',$data['hot_label']);
        if ($data['is_hide']) {
            $checkData['is_hide'] = $data['is_hide'];
        } else {
            $checkData['is_hide'] = 0;
        }
        if ($data['is_hot']) {
            $checkData['is_hot'] = $data['is_hot'];
        } else {
            $checkData['is_hot'] = 0;
        }
        if ($data['is_tj']) {
            $checkData['is_tj'] = $data['is_tj'];
        } else {
            $checkData['is_tj'] = 0;
        }
        if ($data['is_home']) {
            $checkData['is_home'] = $data['is_home'];
        } else {
            $checkData['is_home'] = 0;
        }
        if ($data['is_tuijian']) {
            $checkData['is_tuijian'] = $data['is_tuijian'];
        } else {
            $checkData['is_tuijian'] = 0;
        }
        if ($data['is_ganhuo']) {
            $checkData['is_ganhuo'] = $data['is_ganhuo'];
        } else {
            $checkData['is_ganhuo'] = 0;
        }
        if ($data['is_duanzi']) {
            $checkData['is_duanzi'] = $data['is_duanzi'];
        } else {
            $checkData['is_duanzi'] = 0;
        }
        $checkData['sort_order'] = empty($data['sort_order']) ? 999 : $data['sort_order'];
        $checkData['keywords'] = $data['keywords'] ? $data['keywords'] : $data['title'];
        $checkData['description'] = $data['description'] ? $data['description'] : $data['title'];
        $checkData['link_url'] = $data['link_url'];
        $checkData['content'] = stripcslashes($data['content']);//防止出现编辑器保存内容事出现转码-stripcslashes
        $checkData['phone_content'] = stripcslashes($data['phone_content']);//防止出现编辑器保存内容事出现转码-stripcslashes
        $checkData['heng_dian'] = $data['heng_dian'];
        $checkData['zong_dian'] = $data['zong_dian'];
        $checkData['icon'] = $data['icon'];
        $checkData['introduce'] = $data['introduce'];
        // $checkData['thumb_list'] = !empty($data['thumb_list']) ? json_encode($data['thumb_list']) : '' ;
        // $checkData['thumb'] = $data['thumb'];
        $checkData['files'] = $data['files'];
        $checkData['act'] = $data['act'];

        if(!empty($data['mark'])){
            foreach($data['mark'] as $v){
                if(!empty(trim($v))){
                    $mark[] = $v;
                }
            }
        }
        
        if(!empty($mark)){
            $checkData['mark'] = implode(',',$mark);
        }
        if ($data['is_one']) {
            //数据是通过ckeditor提交的，所以在读取时要使用 stripcslashes() 函数处理一下。
            // $_content = $data['content'];
            $_content = htmlspecialchars_decode($data['content']);
            preg_match_all("/src=\"?(.*?)\"/", $_content, $matchs);

            $checkData['thumb'] = $matchs[1][0];
        } else{
            $checkData['thumb'] = $data['thumb'];
        }
        if(!empty($data['slide_img'])){
            $s_img = $data['slide_img'];
            $s_alt = $data['slide_alt'];
            $s_order = $data['slide_order'];
            for($i=0;$i<count($s_img);$i++){
                $s_order[$i] = empty($s_order[$i])?50:$s_order[$i];
                $pics[] = array(
                    'image'=>$s_img[$i],
                    'alt'=>$s_alt[$i],
                    'order'=>$s_order[$i],
                );
            }
            // dump($pics);
            //排序开始，数组中根据某个元素排序
            $pics = arraySort($pics,'order');
            //排序结束
            // dump($pics);exit;
            sort($pics);
            $checkData['pics'] = json_encode($pics);
        }else{
            $checkData['pics'] = '';
        }

        return $checkData;
    }
    /*
     *文章处理
    */
    public function articleHandle(){
        $data = $this->articleData(input('post.'));
        $pre_kid['desc'] = $data['kind_id'];
        db("config")->where("name='last_add_kind_id'")->update($pre_kid);
        if(empty($data['title'])){
            $json = array('status'=>0,'message'=>'标题不能为空');
            echo json_encode($json);exit;
        }
        $act = $data['act'];
        unset($data['act']);
        if($act == 'add'){
            $r = db('article')->insertGetId($data);
            if ($r) {
                $json['status'] = 1;
                $json['message'] = "添加文章成功！";
                /*********************记录日志***********************/
                addLog(session('user_name').'添加文章成功-'.$data['title'].' [ ID:'.$r.' ]');
                echo json_encode($json);exit;
            } else {
                $json['status'] = 0;
                $json['message'] = "添加文章失败！";
                echo json_encode($json);exit;
            }
        }

        if($act == 'edit'){
            $article_id = $data['article_id'];
            unset($data['article_id']);
            try {
                $r = db('article')->where('article_id='.$article_id)->update($data);
            } catch (ValidateException $e) {
                // 这是进行验证异常捕获
                return json($e->getError());
            } catch (\Exception $e) {
                // 这是进行异常捕获
                return json($e->getMessage());
            }
            // dump($article_id);exit;
            if ($r !== false) {
                $json['status'] = 1;
                $json['message'] = "修改文章成功！";
                /*********************记录日志***********************/
                addLog(session('user_name').'修改文章成功-'.$data['title'].' [ ID:'.$data['article_id'].' ]');
                echo json_encode($json);exit;    
            } else {
                $json['status'] = 0;
                $json['message'] = "修改文章失败！";
                echo json_encode($json);exit;
            }

        }

    }

    function articleReback(){
        $article_id = input('post.article_id');
        $res = db('article')->where(array('article_id'=>$article_id))->find();
        if(!$res){
            $json = ['status'=>0,'message'=>'找不到此文章'];
            echo json_encode($json);exit;
        }else{
            $where['is_del'] = 1;
            $re = db('article')->where(array('article_id'=>$article_id))->update($where);
            if($re!==false){
                $json = ['status'=>1,'message'=>'文章加入回收站成功！'];
                /*********************记录日志***********************/
                addLog(session('user_name').'文章加入回收站成功-'.$res['title'].' [ ID:'.$res['article_id'].' ]');
            }else{
                $json = ['status'=>0,'message'=>'文章加入回收站失败！'];
            }
            echo json_encode($json);exit;
        }
    }
    //批量放入回收站
    function reback_select(){
        $getData = input('get.');
        $ids = $getData['ids'];
        $where['is_del'] = 1;
        if(is_array($ids) && !empty($ids)){
            db('article')->where('article_id','in',implode(',',$ids))->update($where);
            $json = ['status'=>1,'message'=>'操作完成','icon'=>1];
            /*********************记录日志***********************/
            addLog(session('user_name').'文章批量加入回收站成功！-文章 [ ID:'.implode(',',$ids).' ]');
            echo json_encode($json);exit;
        }else{
            $json = ['status'=>0,'message'=>'请选择选项','icon'=>2];
            echo json_encode($json);exit;
        }
    }

    /*
     *文章--回收站列表
    */
    function articleRecycle(){
        $where['is_del']=1;
        $res = Db::name('article')->where($where)->order('article_id desc')->select();
        // $page = $pager->show();//分页显示输出

        $ArticleCat = new ArticleKind(); 
        $cats = $ArticleCat->article_kind_list(0,0,false);
        $cat_list = $ArticleCat->article_kind_list(0, 0, ture);//搜索条件栏目
        $this->assign('cat_select',$cat_list);

        if($res){
            foreach ($res as $val){
                $val['category'] = $cats[$val['kind_id']]['kind_name'];
                $val['add_time'] = $val['add_time'];                
                $list[] = $val;
            }
        }
        $this->assign('list',$list);

        return view('articleRecycle');
    }

    /*
     *文章--加入回收站还原处理
    */
    function articleEndReback(){
        $data = input('post.');
        $re = Db::name('article')->where(array('article_id'=>$data['article_id']))->find();
        if (!$re) {
            $json['status'] = 0;
            $json['message'] = "找不到此文章！";
            echo json_encode($json);
            return;
        } else {
            $where['is_del'] = 0;
            $r = Db::name('article')->where(array('article_id'=>$data['article_id']))->update($where);
            
            if($r!=false) {
                $json['status'] = 1;
                $json['message'] = "文章还原成功！";
                echo json_encode($json);
                return;
            } else {
                $json['status'] = 0;
                $json['message'] = "文章还原失败！";
                echo json_encode($json);
                return;
            } 
        }
    }
    /*
     *文章--彻底删除处理
    */
    function articleEnddel(){
        $data = input('post.');
        $re = Db::name('article')->where(array('article_id'=>$data['article_id']))->find();
        if (!$re) {
            $json['status'] = 0;
            $json['message'] = "找不到此文章！";
            echo json_encode($json);
            return;
        } else {
            $r = Db::name('article')->where(array('article_id'=>$data['article_id']))->delete();
            
            if($r!=false) {
                $json['status'] = 1;
                $json['message'] = "删除文章成功！";
                echo json_encode($json);
                return;
            } else {
                $json['status'] = 0;
                $json['message'] = "删除文章失败！";
                echo json_encode($json);
                return;
            } 
        }
    }
    //文章--彻底删除选中
    function delselect(){
        $getData = input('get.');
        $ids = $getData['ids'];
        if(is_array($ids) && !empty($ids)){
            Db::name('article')->where("article_id in (".implode(',',$ids).")")->delete();
            $json = array('status'=>1,'message'=>'操作完成','icon'=>1);
            echo json_encode($json);exit;
        }else{
            $json = array('status'=>0,'message'=>'请选择选项','icon'=>2);
            echo json_encode($json);exit;
        }
    }

    /*
    **复制文章
    */
    function articlecopy(){
        $id = input('post.article_id');
        $data = db("Article")->where(array('article_id'=>$id))->find();
        unset($data['article_id']);
        $re = db("Article")->insertGetId($data);
        if ($re!==false){
            $json['status'] = 1;
            $json['message'] = '复制文章成功';
            /*********************记录日志***********************/
            // addLog(session('user_name').'复制文章成功-'.$data['title'].' [ ID:'.$data['article_id'].' ]');
        } else {
            $json['status'] = 0;
            $json['message'] = '复制文章失败';
        }
        echo json_encode($json);return;
    }


}
?>